extends Node2D

@onready var area = $Area2D
@onready var collision = $Area2D/CollisionShape2D
@onready var util = Util.new()

# 商店刷新列表
# 这些是商店能卖的东西, 之后通过随机数挑选商品上架
@onready var props = [
	load("res://Props/tscn/potion/CurePotion.tscn"),
	load("res://Props/tscn/potion/InvisiblePotion.tscn"),
	load("res://Props/tscn/potion/SpeedPotion.tscn"),
	load("res://Props/tscn/potion/PowerPotionI.tscn"),
	load("res://Props/tscn/potion/PowerPotionII.tscn"),
	load("res://Props/tscn/potion/ImmunePotion.tscn"),
	load("res://Props/tscn/potion/ArmorPotion.tscn"),
	load("res://Props/tscn/boom/BoomGoods.tscn")
]

var isEnter = false
var propObj = null
var player = null
var money = null		## 钱UI


func _ready():
	area.connect("body_entered", bodyEntered)
	area.connect("body_exited", bodyExited)
	# 生成商品
	var index = RandomNumberGenerator.new().randi_range(0, len(props) - 1)
	propObj = props[index].instantiate()
	propObj.position = Vector2(0, -15)
	var area = util.findOne("$[Area2D]", propObj)
	
	if area != null:
		var propCollision = util.findOne("$[CollisionShape2D]", area)
		# 商店的商品不以碰撞体的形式加入玩家背包
		# 由商店直接放入背包, 直接调用玩家的collection方法
		propCollision.disabled = true
	self.add_child(propObj)

func bodyEntered(body):
	if body.name == "Player":
		isEnter = true
		player = body
		self.money = body.money
		
		
func bodyExited(body):
	if body.name == "Player":
		isEnter = false
		player = null
		
		
func _process(_delta):
	if isEnter && Input.is_action_just_pressed("interactive"):
		# 购买前检测前是不是够
		if self.money.getNum() < propObj.price:
			print("钱不够")
			return
			
		# 炸弹是特殊商品, 累加1即可
		if propObj.name == "BoomGoods":
			player.boomUI.add()
			self.visible = false
			collision.set_deferred("disabled", true)
			
		# 购买商品
		elif player.collection(propObj):
			# 购买成功后的操作
			# 禁用商品碰撞体, 隐藏商品
			# 防止二次购买
			self.visible = false
			collision.set_deferred("disabled", true)
			
		# 代码执行到这里代表购买已经完毕
		# 扣除金钱
		money.subX(propObj.price)
		
		
